package com.dd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dd.common.response.ResultCode;
import com.dd.common.password.RsaPassword;
import com.dd.pojo.entry.User;
import com.dd.common.expection.BizException;
import com.dd.service.UserService;
import com.dd.mapper.UserMapper;
import com.dd.common.utils.JwtUtil;
import com.dd.common.utils.RSAUtil;
import com.dd.common.utils.ShortIdWorker;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;


@Service
@RequiredArgsConstructor
public class UserServiceImpl  implements UserService{

    private final UserMapper userMapper;

    @Override
    public void userRegister(User user) {
        List<User> userInfo = userMapper.selectList( new LambdaQueryWrapper<User>()
                .eq(User::getUserCount,user.getUserCount())
                .or()
                .eq(User::getUserPhone,user.getUserPhone())
                .or()
                .eq(User::getUserEmail,user.getUserEmail()));

        if(userInfo==null||userInfo.size()>0){
            throw new BizException( ResultCode.USER_ACCOUNT_EXIT);
        }
        user.setUserId(ShortIdWorker.getInstance().nextId());
        user.setUserPassword(RSAUtil.encrypt1(user.getUserPassword(), RsaPassword.RSA_PUBLIC_KEY));
        userMapper.insert(user);

    }

    @Override
    public String userLogin(User user) {

        User userInfo = userMapper.selectOne(new LambdaQueryWrapper<User>().isNotNull(User::getUserCount).eq(User::getUserCount,user.getUserCount())
                .or().isNotNull(User::getUserPhone).eq(User::getUserPhone,user.getUserPhone())
                .or().isNotNull(User::getUserEmail).eq(User::getUserEmail,user.getUserEmail()));
        if(Objects.isNull(userInfo)){
            throw  new BizException(ResultCode.USERNAME_NOT_EXIT);
        }

        else  if(!RSAUtil.decrypt1(userInfo.getUserPassword(),RsaPassword.RSA_PRIVATE_KEY).equals(user.getUserPassword())){
            throw  new BizException(ResultCode.USERNAME_OR_PASSWORD_ERROR);
        }

        String token = JwtUtil.generateTokenByNmae(userInfo.getUserId(),userInfo.getUserCount());

        return token;
    }
}




